package de.ama.crawler;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import de.ama.util.Util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ama
 * Date: 14.02.11
 * Time: 18:06
 * To change this template use File | Settings | File Templates.
 */
public class Entry {
    private static int idGen = -1;

    private String path;
    private String searchString;
    private int id = idGen--;
    private long time;
    private String title;
    private String imagePath;
    private String posterPath;
    private String plot;
    private String text = "";
    private String tags ="Neu";
    private List<Entry> matches;
    private boolean queried;
    private transient boolean selected;

    public Entry(String path) {
        setPath(path);
        addTag("Neu");
    }

    public String getTags() {
        return Util.safeToString(tags);
    }

    public void addTag(String tag) {
        if (tags == null) {
            tags = "";
        }

        if (!tags.contains(tag)) {
            tags = tags + "." + tag;
            Store.get().setDirty(true);
        }
    }

    public void clearTags() {
        if(tags!=null){
            Store.get().setDirty(true);
            tags = null;
        }
    }

    public void removeTag(String tag) {
       if(tags==null) return;
       tags = tags.replace(tag,"");
       tags = tags.replace("..",".");
       Store.get().setDirty(true);
    }

    public boolean hasTag(String tag) {
        if(tags==null) return false;
        return tags.contains(tag);
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

    public boolean isQueried() {
        return queried;
    }

    public void setQueried(boolean queried) {
        this.queried = queried;
        Store.get().setDirty(true);
    }

    private void setPath(String path) {
        this.path = normalizePath(path);
        Store.get().setDirty(true);
    }

    public static String normalizePath(String path) {
        String ret = path.replace('\\', '/');
        if (ret.contains(":/")) {
            ret = ret.substring(ret.indexOf(":/") + 2);
        }
        return ret;
    }

    public String getPath() {
        return path;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
        Store.get().setDirty(true);
    }

    public String getImagePath() {
        return imagePath;
    }

    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
        Store.get().setDirty(true);
    }

    public String getPosterPath() {
        return posterPath;
    }

    public void setPosterPath(String posterPath) {
        this.posterPath = posterPath;
        Store.get().setDirty(true);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
        Store.get().setDirty(true);
    }

    public long getTime() {
        if("? ? ?".equals(getTitle())){
            return System.currentTimeMillis();
        }

        return time;
    }

    public void setTime(long time) {
        this.time = time;
        Store.get().setDirty(true);
    }

    public String getPlot() {
        return Util.safeToString(plot);
    }

    public void setPlot(String plot) {
        this.plot = plot;
        Store.get().setDirty(true);
    }

    public List<Entry> getMatches() {
        if (matches == null) {
            matches = new ArrayList<Entry>();
        }
        return matches;
    }

    public boolean isUnknown() {
        if (Util.isEmpty(getTitle())) return true;
        if (Util.isEmpty(getPosterPath())) return true;
        if (Util.isEmpty(getImagePath())) return true;
        if (Util.isEmpty(getPlot())) return true;
        if (Util.isEmpty(getText())) return true;
        return false;
    }

    public void setSearchString(String searchString) {
        this.searchString = searchString;
        Store.get().setDirty(true);
    }

    public String getSearchString() {
        if (searchString == null) {
            try {
                if (getPath().contains("__")) {
                    int start = getPath().indexOf("__")+2;
                    int stop  = getPath().indexOf("/",start);
                    searchString = getPath().substring(start,stop);
                } else {
                    searchString = new File(path).getName();
                }
            } catch (Exception e) {
                searchString = getPath();
            }

            for(String type:Config.get().getTypes()){
                searchString = Util.removeTrailingStringIgnoreCase(searchString, "."+type);
            }
            searchString = searchString.replace("ae","ä");
            searchString = searchString.replace("ue","ü");
            searchString = searchString.replace("oe","ö");
            searchString = searchString.replace("AE","Ä");
            searchString = searchString.replace("UE","Ü");
            searchString = searchString.replace("OE","Ö");
            searchString = searchString.replace('_', ' ');
            searchString = searchString.replace('.', ' ');
            searchString = Util.escapeText(searchString);
            searchString = searchString.trim();
        }
        return searchString;
    }

    public String calcImageName() {
        String string = getSearchString();
        if (Util.isEmpty(string)) {
            return "img_" + System.currentTimeMillis();
        }
        return string.replace(" ", "_");
    }

    public void setText(String text) {
        this.text = text;
        Store.get().setDirty(true);
    }

    public void addText(String pre, String txt) {
        if (Util.isEmpty(txt)) return;
        text += "\n" + pre + txt;
    }

    public String getText() {
        return text;
    }

    public boolean isAmbigous() {
        return getMatches().size() > 0;
    }

    public boolean containsString(String str) {
        str = str.toLowerCase();
        if (Util.safeToString(title).toLowerCase().indexOf(str) >= 0) return true;
        if (Util.safeToString(path).toLowerCase().indexOf(str) >= 0) return true;
        if (Util.safeToString(text).toLowerCase().indexOf(str) >= 0) return true;
        if (Util.safeToString(plot).toLowerCase().indexOf(str) >= 0) return true;
        return false;
    }

    public void save() {
        try {
            String path = getPath() + ".xml";
            XStream xstream = new XStream(new DomDriver());
            xstream.alias("movie", Entry.class);
            xstream.toXML(this, new OutputStreamWriter(new FileOutputStream(path), "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Entry read(File file) {
        Entry entry = null;
        try {
            File infFile = new File(file.getAbsolutePath() + ".xml");
            if (infFile.exists()) {
                XStream xstream = new XStream(new DomDriver());
                xstream.alias("movie", Entry.class);
                entry = (Entry) xstream.fromXML(new InputStreamReader(new FileInputStream(infFile), "UTF-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (entry == null) {
            entry = new Entry(file.getAbsolutePath());
        }

        if (entry.getTime() == 0) {
            entry.setTime(file.lastModified());
        }

        return entry;
    }

}
